package io.jee.runshan.handler;
import io.jee.runshan.domain.remote.weixin.InputMessage;
import io.jee.runshan.domain.remote.weixin.MsgType;
import io.jee.runshan.filter.WeixinOather2Filter;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class WeixinReceiverMemberHandler {
	private static final Logger logger = LoggerFactory.getLogger(WeixinOather2Filter.class);
	
	public void receiver(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			ServletInputStream in = request.getInputStream();
			XStream xs = new XStream(new DomDriver());
			xs.alias("xml", InputMessage.class);
			StringBuilder xmlMsg = new StringBuilder();
			byte[] b = new byte[4096];
			for (int n; (n = in.read(b)) != -1;) {
				xmlMsg.append(new String(b, 0, n, "UTF-8"));
			}
			logger.debug(xmlMsg.toString());
			InputMessage inputMsg = (InputMessage) xs.fromXML(xmlMsg.toString());
			
			String msgType = inputMsg.getMsgType();
			if (msgType.equals(MsgType.Text.toString())) { // 文本消息(关键字匹配自动回复)
				WeixinReceiverTextHandler handler = new WeixinReceiverTextHandler();
				String result = handler.excute(inputMsg);
				response.getWriter().write(result);
			} else if (msgType.equals(MsgType.Voice.toString())) { // 语音问题处理
				WeixinReceiverVoiceHandler handler = new WeixinReceiverVoiceHandler();
				String msg = handler.excute(inputMsg, request);
				if (msg != null) {
					response.getWriter().write(msg);
				}
			} else if (msgType.equals("event")) { // 菜单处理
				WeixinReceiverEventHandler handler = new WeixinReceiverEventHandler();
				String result = handler.excute(inputMsg);
				response.getWriter().write(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
